import gc
import time
from threading import Thread

import keyboard
import pyperclip
from win11toast import toast

from src.main.python.com.wutong.livepet.liveWidget import LiveWidget
from src.main.python.com.wutong.livepet.liveWidget.components import Component
from src.main.python.com.wutong.livepet.liveWidget.components.PetChat import PetChat


class Translation(Component):
    def __init__(self,
                 petChat: PetChat,
                 outLanguage: str = "中文",
                 hotkey: str = "alt+k"):
        super().__init__(componentName="Translation")
        self.petChat = petChat
        self.outLanguage = outLanguage
        self.hotkey = hotkey

    def execute(self):
        Thread(target=lambda: toast("Translation Component", "接收到内容，开始翻译")).start()
        time.sleep(0.2)
        keyboard.press_and_release('ctrl+c')
        time.sleep(0.2)
        text = pyperclip.paste()
        pyperclip.copy('')  # 清空

        system = (f"In the following conversation, "
                  f"you only need to translate the text I provide from auto to {self.outLanguage}. "
                  f"No other content needs to be answered. If no content is entered, please return None."
                  f"Pay attention to distinguish professional terms. "
                  f"If they are professional terms, please bold them in the answer results using markdown grammar."
                  f"If the input text is in the target language, then translate it to the source language.")

        try:
            self.petChat.generate(text, system=system)
        except Exception:
            time.sleep(0.5)
            self.petChat.generate(text, system=system)

    def initUI(self):
        pass

    def componentRunnable(self, liveWidget: LiveWidget) -> bool:
        keyboard.add_hotkey(self.hotkey, self.execute)
        return True

    def componentRelease(self) -> bool:
        keyboard.remove_hotkey(self.hotkey)
        gc.collect()
        return True
